# coding=UTF-8
import datetime
import random

from bs4 import BeautifulSoup

from database.mapper import funds_info, funds_info_his
from utils import date_util, http_util

url = 'http://fund.eastmoney.com/js/fundcode_search.js'
url1 = 'https://push2.eastmoney.com/api/qt/ulist.np/get?cb=jQuery18308106396323091587_1593671935494&fltt=2&invt=2&ut=267f9ad526dbe6b0262ab19316f5a25b&fields=f3,f12,f14&secids=1.600383,0.000656,1.600048,0.000002,0.000069,0.000671,0.001979,0.002146,1.601155,0.000961&_=1593671935724'


# 季度涨幅 url 地址
# http://fundf10.eastmoney.com/jndzf_005968.html
# http://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=quarterzf&code=005968&rt=0.29795761120683595


def detail_info(fund_info):
    code = fund_info.get('fund_code')
    res = funds_info.select_fund_one(code)
    if not res or date_util.diff_days(res['up_time'], date_util.get_date_time()) > 5:
        print(code + "获取基金详细信息")
        rt_list = ['0.7066729178833983', '0.9890302695875468', '0.3440840184855922', '0.0024700778759517705',
                   '0.004676314518826885', '0.32620867910252427']
        year = str(datetime.datetime.now().year)
        req_url = 'http://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=jjcc&' \
                  'code=' + code + '&topline=20&year=' + year + '&month=&rt=' + rt_list[random.randint(0, 5)]
        # a = 'var apidata={ content:"",arryear:[],curyear:2020};'
        # resp = requests.get(req_url)
        resp_content = str(http_util.request_get(req_url).content.decode('utf-8'))
        soup = BeautifulSoup(resp_content, 'html')  # html.parser是解析器，也可是lxml
        tbody_list = soup.select('tbody')
        if len(tbody_list) == 0:
            fund_info['code'] = '0'
            fund_info['name'] = '默认'
            fund_info['ratio'] = 0
            fund_info['hold_hard'] = 0
            fund_info['stock_val'] = 0
            fund_info['total_val'] = 0
            funds_info.insert(fund_info)
            print(code + '未查询到股票详情')
            return
        fund_list = []
        for info in tbody_list[0].children:
            info_contents = info.contents
            contents_len = len(info_contents)
            stock_detail = {}
            if contents_len == 7:
                stock_detail['code'] = info_contents[1].string
                stock_detail['name'] = info_contents[2].string
                if info_contents[4].string == '---':
                    continue
                stock_detail['ratio'] = float(info_contents[4].string[:-1])
                stock_detail['hold_hard'] = str(float(info_contents[5].string.replace(',', '')))
                stock_detail['stock_val'] = int(float(info_contents[6].string.replace(',', '')))
                if float(info_contents[4].string[:-1]) == 0:
                    print(code + '::::' + stock_detail['code'] + '占比为零')
                    continue
                else:
                    stock_detail['total_val'] = int(
                        float(info_contents[6].string.replace(',', '')) / float(info_contents[4].string[:-1]) * 100)
            elif contents_len == 9:
                stock_detail['code'] = info_contents[1].string
                stock_detail['name'] = info_contents[2].string
                if info_contents[6].string == '---':
                    continue
                stock_detail['ratio'] = float(info_contents[6].string[:-1])
                stock_detail['hold_hard'] = str(float(info_contents[7].string.replace(',', '')))
                stock_detail['stock_val'] = int(float(info_contents[8].string.replace(',', '')))
                if float(info_contents[6].string[:-1]) == 0:
                    print(code + '::::' + stock_detail['code'] + '占比为零')
                    continue
                else:
                    stock_detail['total_val'] = int(
                        float(info_contents[8].string.replace(',', '')) / float(info_contents[6].string[:-1]) * 100)
            elif contents_len == 6:
                stock_detail['code'] = info_contents[1].string
                stock_detail['name'] = info_contents[2].string
                info_contents_sub = info_contents[5].select('td')
                if info_contents_sub[0].string == '---':
                    continue
                stock_detail['ratio'] = float(info_contents_sub[0].string[:-1])
                stock_detail['hold_hard'] = str(float(info_contents_sub[1].string.replace(',', '')))
                stock_detail['stock_val'] = int(float(info_contents_sub[2].string.replace(',', '')))
                if float(float(info_contents_sub[0].string[:-1])) == 0:
                    print(code + '::::' + stock_detail['code'] + '占比为零')
                    continue
                else:
                    stock_detail['total_val'] = int(
                        float(info_contents_sub[2].string.replace(',', '')) / float(
                            info_contents_sub[0].string[:-1]) * 100)
            else:
                print('error' + str(info_contents))
                print('error' + str(contents_len))
                continue
            fund_list.append(dict(stock_detail, **fund_info))
        try:
            # 历史数据备份
            f_list = funds_info.select_fund_code(code)
            funds_info_his.insert_mul(f_list, date_util.parse_date_str(f_list[0]['up_time']))
            # 更新数据
            funds_info.delete_fund(code)
            funds_info.insert_mul(fund_list)
        except:
            print(fund_info)
            print(fund_list)


# 获取所有的股票型基金
def get_info():
    # resp1 = requests.get(url)
    # http_util.request_get(url)
    resp1_content = str(http_util.request_get(url).content.decode('utf-8'))
    fund_list = resp1_content.split('[[')[1].split(']]')[0]
    # ["000001","HXCZHH","华夏成长混合","混合型","HUAXIACHENGZHANGHUNHE"]
    for fund_str in fund_list.split('],['):
        fund_str = fund_str.replace('\"', '')
        fund_info_list = fund_str.split(',')
        fund_info = {'fund_code': fund_info_list[0],
                     'fund_name': fund_info_list[2],
                     'type': fund_info_list[3],
                     'short_name': fund_info_list[1],
                     'full_name': fund_info_list[4],
                     'attribute': '股票型基金'}
        detail_info(fund_info)


if __name__ == '__main__':
    print("start")
    get_info()
    # detail_info({'fund_code': '163418'})
    # get_info()
    print('end')
